#include <bits/stdc++.h>
using namespace std;

struct ListNode {
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};

class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        if(head == NULL || head->next==NULL) return NULL; 
        ListNode *slow = head->next; ListNode *fast = slow->next;
        while(fast!=NULL && slow!=fast){
            slow = slow->next;
            fast = fast->next;
            if(fast != NULL) fast = fast->next;
        }
        if(fast == NULL) return NULL;
        ListNode *ptr = head;
        while(ptr != slow){
            ptr = ptr->next;
            slow = slow->next;
        }

        return ptr;
    }
};